package com.taoyige.ui;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.R.id;
import com.taoyige.R.layout;
import com.taoyige.R.menu;
import com.taoyige.bean.Address;
import com.taoyige.bean.AddressList;
import com.taoyige.bean.Goods;
import com.taoyige.bean.Order;
import com.taoyige.bean.Result;
import com.taoyige.bean.User;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 增加地址信息
 * @author zhuxun
 * @version 1.0
 * @date 2014-11-25 上午9:56:40
 */
public class AddAddressActivity extends BaseActivity {
	
	private AppContext appContext;
	private Handler handlerA;
	private Handler handlerB;
	private LoadingDialog loading;
	private ImageButton returnBack;
	private ImageButton homePage;
	private TextView userHeadText;
	private Spinner userprovince;
	private ArrayAdapter<String> provinceAdapter;
	private ArrayAdapter<String> cityAdapter;
	private ArrayAdapter<String> townAdapter;
	private List<String> allLocation1;
	private List<String> allLocation2;
	private List<String> allLocation3;
	private Spinner usercity;
	private Spinner usertown;
	private InputStream inputStream;
	private JSONObject location;
	
	private Address locationId;
	private Address address;
	private EditText userName;
	private EditText userPhone;
	private EditText userZip;
	private EditText addressDetail;
	
	private String userId="0";
	private List<Address> addressList;
	private int status=0;
	private int provinceId=0;
	private int cityId=0;
	private int countyId=0;
	private String provinceValue="-1";
	private String cityValue="-1";
	private String countyValue="-1";
	
	private LinearLayout add_location_body;
	private Button addressSave;
	private RelativeLayout addressSaveC;
	private int fromStatus;
	private Order order;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_location);
		appContext=(AppContext) getApplication();
		userId=appContext.getLoginUid();
		this.initView();
		if (!appContext.isNetworkConnected()){
			homePage.setOnClickListener(homeOnClickListener);
			returnBack.setOnClickListener(homeOnClickListener);
			add_location_body.setVisibility(View.INVISIBLE);
			addressSaveC.setVisibility(View.INVISIBLE);
			return;
		}
		this.initData();
	}
	
	private void initView(){
		order=(Order)getIntent().getSerializableExtra("order");
		fromStatus=getIntent().getIntExtra("status", 0);
		locationId=(Address)getIntent().getSerializableExtra("address");
		
		returnBack=(ImageButton)findViewById(R.id.user_hear_return_back);
		homePage=(ImageButton)findViewById(R.id.user_hear_homePage);
		userHeadText=(TextView)findViewById(R.id.user_hear_text);
		userHeadText.setText("编辑收货地址");
		add_location_body=(LinearLayout)findViewById(R.id.add_location_body);
		addressSave=(Button)findViewById(R.id.useraddresssave);
		addressSaveC=(RelativeLayout)findViewById(R.id.add_location_save_user_address);
		userprovince=(Spinner)findViewById(R.id.add_address_userprovince_value);
		usercity=(Spinner)findViewById(R.id.add_address_usercity_value);
		usertown=(Spinner)findViewById(R.id.add_address_usertown_value);
		
		inputStream=this.getResources().openRawResource(R.raw.locations);
		
		userName=(EditText)findViewById(R.id.add_address_name_value);
		userPhone=(EditText)findViewById(R.id.add_address_phone_value);
		userZip=(EditText)findViewById(R.id.add_address_userzip_value);
		addressDetail=(EditText)findViewById(R.id.add_address_useraddress_value);
	}
	
	private void initData() {
		userprovince.setOnItemSelectedListener(new userprovinceListener());
		usercity.setOnItemSelectedListener(new usercityListener());
		returnBack.setOnClickListener(returnOnClickListener);
		homePage.setOnClickListener(homeOnClickListener);
		addressSave.setOnClickListener(saveAddressListener);
		setAddressId();
	}
	
	private void setAddressId(){
		if(locationId.getId().equals("-1")){
			status=1;
		}else{
			userName.setText(locationId.getName());
			userPhone.setText(String.valueOf(locationId.getMobilephone()));
			userZip.setText(String.valueOf(locationId.getPostcode()));
			addressDetail.setText(locationId.getDetails());
			provinceValue = locationId.getProvince();
			cityValue = locationId.getCity();
			countyValue = locationId.getCounty();
		}
					
		allLocation1 = new ArrayList<String>();
		allLocation1.add("请选择");
		for(int i=0;i<addressIdList.size();i++){
			if(addressIdList.get(i).equals(provinceValue)){
				provinceValue=addressNameList.get(i);
			}
			if(addressClassList.get(i).equals("1")){
				allLocation1.add(addressNameList.get(i));
				if(addressNameList.get(i).equals(provinceValue)){
					provinceId=allLocation1.size()-1;
				}
			}
		}
		provinceAdapter = new ArrayAdapter<String>(AddAddressActivity.this, R.layout.spinner_location, allLocation1);
		provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		userprovince.setAdapter(provinceAdapter);
		if(status!=1){
			userprovince.setSelection(provinceId, true);
			provinceId=0;
		}
	}
	
	public class userprovinceListener implements OnItemSelectedListener{
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if(!allLocation1.get(position).equals("请选择")){
				String province = allLocation1.get(position);
				for(int i=0;i<addressIdList.size();i++){
					if(province.equals(addressNameList.get(i))){
						province=addressIdList.get(i);
						break;
					}
				}
				allLocation2 = new ArrayList<String>();
				allLocation2.add("请选择");
				for(int i=0;i<addressIdList.size();i++){
					if(addressIdList.get(i).equals(cityValue)){
						cityValue=addressNameList.get(i);
					}
					if(province.equals(addressClassList.get(i))){
						allLocation2.add(addressNameList.get(i));
						if(addressNameList.get(i).equals(cityValue)){
							cityId=allLocation2.size()-1;
						}
					}
				}
			}else{
				allLocation2 = new ArrayList<String>();
				allLocation2.add("请选择");
			}
				cityAdapter = new ArrayAdapter<String>(AddAddressActivity.this,R.layout.spinner_location, allLocation2);
				cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				usercity.setAdapter(cityAdapter);
				if(status!=1){
					usercity.setSelection(cityId, true);
					cityId=0;
				}
			}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	}
	
	public class usercityListener implements OnItemSelectedListener{
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if(!allLocation2.get(position).equals("请选择")){
				String city = allLocation2.get(position);
				for(int i=0;i<addressIdList.size();i++){
					if(city.equals(addressNameList.get(i))){
						city=addressIdList.get(i);
						break;
					}
				}
				allLocation3 = new ArrayList<String>();
				allLocation3.add("请选择");
				for(int i=0;i<addressIdList.size();i++){
					if(addressIdList.get(i).equals(countyValue)){
						countyValue=addressNameList.get(i);
					}
					if(city.equals(addressClassList.get(i))){
						allLocation3.add(addressNameList.get(i));
						if(addressNameList.get(i).equals(countyValue)){
							countyId=allLocation3.size()-1;
						}
					}
				}
			}else{
				allLocation3 = new ArrayList<String>();
				allLocation3.add("请选择");
			}
				townAdapter = new ArrayAdapter<String>(AddAddressActivity.this,R.layout.spinner_location, allLocation3);
				townAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				usertown.setAdapter(townAdapter);
				if(status!=1){
					usertown.setSelection(countyId, true);
					countyId=0;
				}
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	}
	
	public View.OnClickListener userListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			UIHelper.showUser(v.getContext());
		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent( AddAddressActivity.this, AddressDetailActivity.class);
			intent.putExtra("order", order);
			if(fromStatus==1||fromStatus==2){
				intent.putExtra("status", fromStatus);
			}
			AddAddressActivity.this.startActivity(intent);
			finish();
		} 
		return flag;
	}
	
	private View.OnClickListener saveAddressListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
            	saveAddress();
		}
	};
	
	private void saveAddress() {
			if(userName.getText().length()==0){
				userName.setHint("用户姓名不能为空");
				userName.setHintTextColor(getResources().getColor(R.color.red));
				UIHelper.ToastMessage(AddAddressActivity.this, "用户姓名不能为空");
			}else if(userPhone.getText().length()==0){
				userPhone.setHint("联系电话不能为空");
				userPhone.setHintTextColor(getResources().getColor(R.color.red));
				UIHelper.ToastMessage(AddAddressActivity.this, "联系电话不能为空");
			}else if(userPhone.getText().length()!=11){
				UIHelper.ToastMessage(AddAddressActivity.this, "手机号码位数不正确");
			}else if(userprovince.getSelectedItem().toString().equals("请选择")){
				UIHelper.ToastMessage(AddAddressActivity.this, "请选择省份");
			}else if(usercity.getSelectedItem().toString().equals("请选择")){
				UIHelper.ToastMessage(AddAddressActivity.this, "请选择城市");
			}else if(userZip.getText().length()==0){
				userZip.setHint("邮编不能为空");
				userZip.setHintTextColor(getResources().getColor(R.color.red));
				UIHelper.ToastMessage(AddAddressActivity.this, "邮编不能为空");
			}else if(userZip.getText().length()!=6){
				UIHelper.ToastMessage(AddAddressActivity.this, "邮政编码位数不正确");
			}else if(addressDetail.getText().length()==0){
				addressDetail.setHint("详细地址不能为空");
				addressDetail.setHintTextColor(getResources().getColor(R.color.red));
				UIHelper.ToastMessage(AddAddressActivity.this, "详细地址不能为空");
			}else{
				address=new Address();
				address.setName(userName.getText().toString());
				address.setMobilephone(userPhone.getText().toString());
				address.setPostcode(Integer.valueOf(userZip.getText().toString()));
				address.setDetails(addressDetail.getText().toString());
				int getstatus=0;
				for(int y=0;y<addressIdList.size();y++){
					if(userprovince.getSelectedItem().toString().equals(addressNameList.get(y))){
						address.setProvince(addressIdList.get(y));
						getstatus++;
					}
					if(usercity.getSelectedItem().toString().equals(addressNameList.get(y))){
						address.setCity(addressIdList.get(y));
						getstatus++;
					}
					if(usertown.getSelectedItem().toString().equals(addressNameList.get(y))||usertown.getSelectedItem().toString().equals("请选择")){
						if(usertown.getSelectedItem().toString().equals("请选择")){
							address.setCounty("-1");
						}else{
							address.setCounty(addressIdList.get(y));
						}
						getstatus++;
					}
					if(getstatus==3){
						break;
					}
				}
				
				if(!locationId.getId().equals("-1")){
					address.setId(locationId.getId());
					handlerA = new Handler() {
						public void handleMessage(Message msg) {
							if (loading != null)
								loading.dismiss();
							if (msg.what == 1 && msg.obj != null) {
								Address result = (Address) msg.obj;
								if(result.getResult().getErrorCode()==200){
									if(fromStatus==1||fromStatus==2){
										Intent intent = new Intent( AddAddressActivity.this, AddressDetailActivity.class);
										intent.putExtra("order", order);
										intent.putExtra("status", fromStatus);
										intent.putExtra("dosomething", 1);
										AddAddressActivity.this.startActivity(intent);
										finish();
									}else{
										Intent intent = new Intent(AddAddressActivity.this, AddressDetailActivity.class);
										intent.putExtra("order", order);
										intent.putExtra("dosomething", 1);
										AddAddressActivity.this.startActivity(intent);
										finish();
									}
								}else{
									UIHelper.ToastMessage(AddAddressActivity.this, "网络异常，更新失败");
								}
							}else if (msg.obj != null) {
								((AppException) msg.obj).makeToast(AddAddressActivity.this);
							}
						}
					};
					loadAddresssInfomationThreadA();
				}else{
					address.setUserID(locationId.getUserID());
					handlerB = new Handler() {
						public void handleMessage(Message msg) {
							if (loading != null)
								loading.dismiss();
							if (msg.what == 1 && msg.obj != null) {
								Address result = (Address) msg.obj;
								if(result.getResult().getErrorCode()==200){
									if(fromStatus==1){
										Intent intent = new Intent( AddAddressActivity.this, AddressDetailActivity.class);
										intent.putExtra("order", order);
										intent.putExtra("status", fromStatus);
										intent.putExtra("dosomething", 2);
										AddAddressActivity.this.startActivity(intent);
										finish();
									}else{
										Intent intent = new Intent(AddAddressActivity.this, AddressDetailActivity.class);
										intent.putExtra("order", order);
										intent.putExtra("dosomething", 2);
										AddAddressActivity.this.startActivity(intent);
										finish();
									}
								}else{
									UIHelper.ToastMessage(AddAddressActivity.this, "网络异常，保存失败");
								}
							}else if (msg.obj != null) {
								((AppException) msg.obj).makeToast(AddAddressActivity.this);
							}
						}
					};
					loadAddresssInfomationThreadB();
				}
			}
	}
	
	private void loadAddresssInfomationThreadA() {
		
		loading = new LoadingDialog(this);
		loading.show();
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Address result=((AppContext) getApplication()).addrUpdate(address);
					msg.what = 1;
					msg.obj = result;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handlerA.sendMessage(msg);
			}
		}.start();
	}
	
	private void loadAddresssInfomationThreadB() {
		
		loading = new LoadingDialog(this);
		loading.show();
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Address result=((AppContext) getApplication()).addrAdd(address);
					msg.what = 1;
					msg.obj = result;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handlerB.sendMessage(msg);
			}
		}.start();
	}
		
	
	private View.OnClickListener homeOnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
            	UIHelper.showHomePage(v.getContext());
            	finish();
		}
	};
	
	private View.OnClickListener returnOnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
            	Intent intent = new Intent( v.getContext(), AddressDetailActivity.class);
    			intent.putExtra("order", order);
    			if(fromStatus==1||fromStatus==2){
    				intent.putExtra("status", fromStatus);
    			}
    			v.getContext().startActivity(intent);
    			finish();
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
